<?php


namespace App\Service\WorkOrder\Mission;


use App\Enums\WorkOrder\MissionEnum;
use App\Enums\WorkOrder\OrderEnum;
use App\Models\WorkOrder\WorkOrderApplyMainModel;
use App\Models\WorkOrder\WorkOrderApplyManagerModel;
use App\Models\WorkOrder\WorkOrderApplyManagerSubmitHistoryModel;
use App\Models\WorkOrder\WorkOrderMissionModel;
use App\Models\WorkOrder\WorkOrderOperateLogModel;
use App\Models\WorkOrder\WorkOrderUserRoleModel;
use App\Service\WorkOrder\Manager\ManagerService;
use Illuminate\Support\Facades\DB;

class AutoPassService
{
    const SYS_USER_ID     = 0;
    const SYS_USER_NAME   = '系统';

    public static function waiMaiOpenKeFuPass(WorkOrderApplyMainModel $order):void
    {
        if (!$order->isFunctionWaiMaiOpen()) {
            return;
        }
        $workOrderNo = $order->workOrderNo;

        $problemRole = WorkOrderUserRoleModel::ROLE_TYPE_6;

        $userId = self::SYS_USER_ID;

        DB::beginTransaction();
        $applyManagerDetail = WorkOrderApplyManagerModel::add(
            $workOrderNo, $problemRole,$userId,self::SYS_USER_NAME
        );
        $applyManagerDetail->solution = WorkOrderOperateLogModel::TYPE_TEXT[WorkOrderOperateLogModel::TYPE_17];
        $applyManagerDetail->save();

        WorkOrderApplyManagerSubmitHistoryModel::query()->insert([
            "applyManagerId"  => $applyManagerDetail->id,
            "type"            => WorkOrderApplyManagerSubmitHistoryModel::TYPE_SOLUTION,
            "content"         => WorkOrderOperateLogModel::TYPE_TEXT[WorkOrderOperateLogModel::TYPE_17],
            'createdUsername' => self::SYS_USER_NAME,
            "createdAt"       => time()
        ]);

        WorkOrderMissionModel::add(
            $workOrderNo, MissionEnum::STEP_1, $userId, MissionEnum::MISSION_STATUS_1
        );
        WorkOrderMissionModel::add($workOrderNo, MissionEnum::STEP_2, $userId);
        WorkOrderApplyMainModel::saveStep($workOrderNo, MissionEnum::STEP_2);
        DB::commit();

        WorkOrderOperateLogModel::generateOperateLog(
            $workOrderNo,
            MissionEnum::STEP_2,
            WorkOrderOperateLogModel::TYPE_17,
            self::SYS_USER_NAME,
            $userId
        );

        (new MissionEngineService($workOrderNo))->finish(MissionEnum::STEP_2);
    }
}